using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Authlibcore
{
    public static class AESHelper
    { 
        /// <summary>
        /// 对数据使用公钥进行AES加密
        /// </summary>
        /// <param name="pubkey">公钥</param>
        /// <param name="data">待加密的数据Base64</param>
        /// <returns>加密后的数据</returns>
        public static Task<byte[]> EnAES(string pubkey, string data)
        {  //为了简便，向量直接设置为该base64字符串
            string iv = "eSBph51kXzs9RlvuVuv7FA==";
            using (Aes aes = Aes.Create())
            {
                aes.Key = Convert.FromBase64String(pubkey);
                aes.IV = Convert.FromBase64String(iv);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.KeySize = 256;
                //开始进行加密操作
                using (var encry = aes.CreateEncryptor(Convert.FromBase64String(pubkey), Convert.FromBase64String(iv)))
                {
                    var da1 = Convert.FromBase64String(data);
                    byte[] byteencry = encry.TransformFinalBlock(da1, 0, da1.Length);
                    return Task.FromResult(byteencry);
                }
            }
        }
        /// <summary>
        /// 对数据进行AES解密
        /// </summary>
        /// <param name="pubkey"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static Task<byte[]> DeAES(string pubkey, string data)
        {
            //为了简便，向量直接设置为该base64字符串
            string iv = "eSBph51kXzs9RlvuVuv7FA==";
            using (Aes ass = Aes.Create())
            {
                ass.Key = Convert.FromBase64String(pubkey);
                ass.IV = Convert.FromBase64String(iv);
                ass.Mode = CipherMode.CBC;
                ass.Padding = PaddingMode.PKCS7;
                ass.KeySize = 256;
                using (var dec = ass.CreateDecryptor(Convert.FromBase64String(pubkey), Convert.FromBase64String(iv)))
                {
                    var da1 = Convert.FromBase64String(data);
                    var da2 = dec.TransformFinalBlock(da1, 0, da1.Length);
                    return Task.FromResult(da2);
                }
            }
        }
    }
}
